<template>
    <div class="main">
        <div class="flex-jsb">
            <div>
                <el-menu text-color="#666" active-text-color="#21B794" @select="handleSelect" :default-active="activeIndex"
                    class="el-menu-demo" mode="horizontal">
                    <el-menu-item :index="String(item.ord)" v-for="(item) in safeZoneTypeOpt">{{ item.name }}</el-menu-item>
                </el-menu>
            </div>
            <div class="flex-ac">
                <el-input-number label="描述文字" size="mini" @change="change" :max="100" :min="30" v-model="scale"
                    :step="10"></el-input-number>
                <i class="el-icon-full-screen" @click="fullScreen"></i>
            </div>
        </div>
        <div class="topology-wrap">
            <div id="myDiagramDiv" style="width:100%;height:770px;margin: 0 auto;"></div>
            <div id="toolTipDIV" style="position: absolute; z-index: 1000; display: none;">
                <!-- <p id="toolTipParagraph">Tooltip</p> -->
                <!--节点信息  -->
                <div v-if="type == 1" class="info">
                    <h3> 资产信息 </h3>
                    <div class="flex-jsb">
                        <div class="flex-ac">
                            <div>设备:</div>
                            <div class="text-ov">{{ info.id }}({{ info.type }}) </div>
                        </div>
                        <div class="flex-ac">
                            <div>名称: </div>
                            <div class="text-ov">{{ info.name }}</div>
                        </div>
                    </div>
                    <div class="flex-jsb">
                        <div class="flex-ac">
                            <div>IP:</div>
                            <div>{{ info.commIp }}</div>
                        </div>
                        <div class="flex-ac">
                            <div>CPU:</div>
                            <div>{{ info.cpu }}</div>
                        </div>
                    </div>
                    <div class="flex-jsb">
                        <div class="flex-ac">
                            <div>mem:</div>
                            <div>{{ info.memory }}</div>
                        </div>
                        <div class="flex-ac">
                            <div>工况:</div>
                            <div>{{ info.runStatus == "2" ? "建模" : info.runStatus == "1" ? "测试" : "运行" }}</div>
                        </div>
                    </div>
                    <div class="flex-jsb">
                        <div class="flex-ac">
                            <div>采样时间:</div>
                            <div style="width: 200px;">{{ formatDate(info.updateTime) }}</div>
                        </div>
                    </div>
                </div>
                <!-- 线路信息 -->
                <div v-else class="info">
                    <h3> 线路信息 </h3>
                    <div class="flex-jsb">
                        <div class="flex-ac">
                            <div>设备1:</div>
                            <div class="text-ov">{{ info.fromName }}</div>
                        </div>
                        <div class="flex-ac">
                            <div>端口1: </div>
                            <div class="text-ov">{{ info.fromPort }}{{ info.fromDesc }}</div>
                        </div>
                    </div>
                    <div class="flex-jsb">
                        <div class="flex-ac">
                            <div>设备2:</div>
                            <div>{{ info.toName }}</div>
                        </div>
                        <div class="flex-ac">
                            <div>端口2:</div>
                            <div>{{ info.toPort }}{{ info.toDesc }}</div>
                        </div>
                    </div>
                    <div class="flex-jsb">
                        <div class="flex-ac">
                            <div>速率:</div>
                            <div>{{ info.speed }}</div>
                        </div>
                        <div class="flex-ac">
                            <div>5分钟流入:</div>
                            <div>{{ info.fiveInputBPS }}</div>
                        </div>
                    </div>
                    <div class="flex-jsb">
                        <div class="flex-ac">
                            <div>5分钟流出:</div>
                            <div>{{ info.fiveOutputBPS }}</div>
                        </div>
                        <div class="flex-ac">
                            <div>采样时间:</div>
                            <div>{{ formatDate(info.sampleTime) }}</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <el-dialog title="设备详情" :visible="dialogVisible" width="55%" :before-close="handleClose">
            <div style="width: 100%;">
                <asset-info ref="aseetRef" :resourceId="resourceId" :resourceTypeId="resourceTypeId" />
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { topo } from "@/api/computerRoomApi.js";
import assetApi from '@/api/assetApi'
import { getAction } from '@/utils/httpUtil'
import go from "gojs";
import assetInfo from "@/components/assetInfo/index.vue"
import utils from "@/utils/date.js"

// for conciseness in defining templates
let go$ = go.GraphObject.make;

export default {
    components: { assetInfo },
    data() {
        return {
            safeZoneTypeOpt: [],
            activeIndex: "1",
            myDiagram: {},
            gogo$: {},
            source: {},
            scale: 100,
            type: 1,//1节点弹窗2线路弹窗
            info: {},
            dialogVisible: false,
            resourceId: "",
            resourceTypeId: "",
            timer: "",
            loopTimer: ""
        }
    },
    mounted() {
        // 安全区域
        getAction(assetApi.asset.queryByCode, { name: '安全区域' }).then(res => {
            this.safeZoneTypeOpt = res.info
        })
        this.topo();
        this.init();
        if (this.timer) {
            clearInterval(this.timer)
        }
        this.timer = setInterval(() => {
            this.topo(true)
        }, 1000 * 60);

    },
    computed: {

    },
    methods: {

        handleSelect(index) {
            if (this.activeIndex == index) return;
            this.activeIndex = index;
            this.topo()
        },
        formatDate(date) {
            return utils.formatter(date, "yyyy-MM-dd hh:mm:ss")
        },

        topo(isUpdate = false) {
            topo({ area: this.activeIndex }).then(res => {
                if (res.code == "200") {
                    this.source = res.info;
                    this.load(isUpdate);
                }
            })
        },

        // 全屏展示
        fullScreen() {
            const renderEl = document.querySelector("#myDiagramDiv")
            if (renderEl.requestFullscreen) {
                renderEl.requestFullscreen().then(() => graph.resizeRender());
            }
        },

        handleClose(done) {
            this.dialogVisible = false;
        },

        change(v) {
            this.myDiagram.scale = v / 100;
        },

        init() {
            const _this = this
            if (window.goSamples) goSamples();  // init for these samples -- you don't need to call this
            this.myDiagram = go$(go.Diagram, "myDiagramDiv", {
                // "animationManager.initialAnimationStyle": go.AnimationManager.AnimateLocations,
                contentAlignment: go.Spot.Center,  // content is always centered in the viewport
                // autoScale: go.Diagram.Uniform,  // scale always has all content fitting in the viewport
                "toolManager.hoverDelay": 10,  // how quickly tooltips are shown
            });

            function nodeTypeImage(obj) {
                // console.log(obj);
                let id = obj.resourceTypeId;
                if (obj.highLight == 1) {
                    id += "_2"
                }
                return require(`../../assets/computerRoom/topology/${id}.png`);
            }

            function nodeTypeSize(type) {
                switch (type) {
                    case "415":
                        return new go.Size(52, 33);
                    case "429":
                        return new go.Size(41, 51);
                    case "428":
                        return new go.Size(51, 36);
                    case "434":
                    case "430":
                        return new go.Size(79, 139);
                    default:
                        return new go.Size(46, 52);
                }
            }

            function showToolTip(obj, diagram, tool) {
                if (obj.data.from) {
                    // 线路信息
                    _this.type = 2;
                    const toName = _this.source.nodeDateList.find(({ id }) => id == obj.data.to)
                    if (toName) {
                        obj.data["toName"] = toName.name
                    }
                    const fromName = _this.source.nodeDateList.find(({ id }) => id == obj.data.from)
                    if (fromName) {
                        obj.data["fromName"] = fromName.name
                    }
                } else {
                    // 节点信息
                    _this.type = 1
                }

                _this.info = obj.data;
                var toolTipDIV = document.getElementById('toolTipDIV');
                var pt = diagram.lastInput.viewPoint;
                let x = pt.x + 50;
                let y = pt.y + 130;
                if (y > 600) {
                    y = 600
                }
                if (x > 1000) {
                    x = 1000
                }
                toolTipDIV.style.left = x + "px";
                toolTipDIV.style.top = y + "px";
                toolTipDIV.style.display = "block";
            }

            function hideToolTip(diagram, tool) {
                var toolTipDIV = document.getElementById('toolTipDIV');
                if (toolTipDIV) {
                    toolTipDIV.style.display = "none";
                }
            }

            let myToolTip = go$(go.HTMLInfo, {
                show: showToolTip,
                hide: hideToolTip
            });

            function onSelectionChanged(node) {
                var icon = node.findObject("Icon");
                if (icon !== null) {

                    //判断node的选择状态
                    if (node.isSelected) {
                        icon.source = require(`../../assets/computerRoom/topology/${node.data.resourceTypeId + "_1"}.png`)
                    } else {
                        let id = node.data.resourceTypeId;
                        if (node.data.highLight == 1) {
                            id += "_2"
                        }
                        icon.source = require(`../../assets/computerRoom/topology/${id}.png`)
                    }
                }
            }        
            // 双击事件
            function nodeDoubleClick(e, obj) {
                console.log(obj);
                if (obj.data.resourceId) {
                    _this.resourceId = obj.data.resourceId;
                    _this.resourceTypeId = obj.data.resourceTypeId;
                    _this.dialogVisible = true;
                }
            }
            // 点击事件
            function linkClick(s) {
                console.log(s);
                // document.getElementById("inputEventsMsg").textContent = s;
            }
            function loop() {
                clearTimeout(_this.loopTimer)
                _this.loopTimer = setTimeout(function () { changeColor(); loop(); }, 2000);
            }
            function changeColor() {
                var linkDataArray = _this.myDiagram.model.linkDataArray;
                linkDataArray.map((item) => {
                    if (item.lineStatus == "2") {
                        item.opacity = (item.opacity == 1 ? 0 : 1);
                        _this.myDiagram.model.updateTargetBindings(item);
                    }
                })
            }
            loop();
            // node模版
            this.myDiagram.nodeTemplate =
                go$(go.Node, "Vertical",
                    {
                        // click: nodeClick,
                        doubleClick: nodeDoubleClick,
                        selectionAdorned: false,
                        selectionChanged: onSelectionChanged,
                        locationSpot: go.Spot.Center,
                        margin: new go.Margin(0, 10, 0, 0),
                        toolTip: myToolTip
                        // end Adornment
                    },  // on Panel
                    new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify),
                    go$(go.Panel, "Vertical",
                        go$(go.Picture, { margin: 5, name: "Icon" },
                            // "resourceTypeId"
                            new go.Binding("source", nodeTypeImage),
                            new go.Binding("desiredSize", "type", nodeTypeSize)),
                        go$(go.TextBlock, {
                            font: "10px sans-serif", width: 50, margin: 5, overflow: go.TextBlock.OverflowEllipsis,
                            maxLines: 1
                        }, new go.Binding("text", "name")),
                    ),
                    // end Spot Panel
                );
            // end Node
            // link模版
            this.myDiagram.linkTemplate =
                go$(go.Link, {
                    click: linkClick,
                },
                    go$(go.Shape, { strokeWidth: 1 },
                        new go.Binding("strokeDashArray", "lineStatus", function (n) {
                            if (n == "2") return [3, 3];
                            return [0, 0];
                        }),
                        new go.Binding("opacity", "opacity"),
                    ),  // the link shape

                    go$(go.Shape,   // the arrowhead
                        { toArrow: "OpenTriangle", fill: null }, new go.Binding("opacity", "opacity"),
                    ),
                    {
                        toolTip: myToolTip
                    }

                );
            // this.myDiagram.scale = 0.7;
        },
        // 加载数据
        load(isUpdate = false) {
            let obj = {};

            let nodeDataArray = this.source.nodeDateList.map((item) => {
                if (!obj[item.type]) {
                    obj[item.type] = item.type
                }
                if (!obj[item.resourceTypeId]) {
                    obj[item.resourceTypeId] = item.resourceTypeId
                }
                return {
                    ...item,
                    loc: item.picX + " " + item.picY,
                    key: item.id,
                }
            });

            console.log(obj, this.myDiagram.nodeDataArray);
            let lineDataArray = this.source.lineDateList.map((item) => ({
                ...item,
            }));
            if (isUpdate) {
                nodeDataArray.map((item) => {
                    this.myDiagram.model.setDataProperty(
                        item, "highLight", item.highLight
                    );
                })
                lineDataArray.map((item) => {
                    this.myDiagram.model.setDataProperty(
                        item,
                        "lineStatus",
                        item.lineStatus
                    );
                })
                // nodeDataArray;
                // this.myDiagram.model.lineDataArray = lineDataArray;
            }
            this.myDiagram.model = new go.GraphLinksModel(nodeDataArray, lineDataArray);
        },

    },

}
</script>
<style scoped lang="scss">
.main {
    width: 100%;
    height: 100%;
    overflow: auto;
    margin: 0 auto;
    padding: 16px;
    box-shadow: 0px 0px 12px 0px rgba(129, 155, 151, 0.3);
    border-radius: 10px;
    background-color: #fff;

    .topology-wrap {
        width: 100%;
        height: 80vh;
        overflow: auto;

        #myDiagramDiv {
            background-color: #fff;
        }

        #toolTipDIV {
            background: rgba(0, 0, 0, 0.75);
            box-shadow: 1px 2px 7px 0px rgba(0, 0, 0, 0.6);
            padding: 10px 15px;
            font-size: 12px;
            color: #fff;
            width: 380px;
            border-radius: 10px;

            .info {
                h3 {
                    position: relative;
                    padding-bottom: 10px;

                    &::before {
                        content: "";
                        width: 110%;
                        height: 1px;
                        position: absolute;
                        bottom: 0px;
                        left: -15px;
                        background-color: #e2e2e2;
                    }
                }

                .flex-jsb {
                    margin-top: 10px;

                    div:nth-child(1) {
                        text-align: left;
                        min-width: 20px;
                    }

                    div:nth-child(2) {
                        margin-left: 10px;
                    }
                }
            }

        }
    }

    i {
        display: block;
        font-size: 18px;
        margin: 0px 0 0 20px;
        color: #000;
        text-align: center;
        cursor: pointer;
    }

}

.el-dialog__body {
    padding: 0px 20px;
}
</style>
